package cn.controller;

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.sys.IUserService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.kpi.common.mapper.JsonMapper;
import cn.kpi.common.utils.DateUtils;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.service.sys.IAccountService;
public class BaseController {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private IAccountService iAccountService;

	@Autowired
	private IOrgService iOrgService;

	@Autowired
	private IUserService iUserService;

	@Value("${adminPath}")
	protected String adminPath;
	

	@Value("${frontPath}")
	protected String frontPath;
	
	
	@Value("${urlSuffix}")
	protected String urlSuffix;
	

	
	protected void addMessage(Model model, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		model.addAttribute("message", sb.toString());
	}
	

	protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		redirectAttributes.addFlashAttribute("message", sb.toString());
	}
	
	
	protected String renderString(HttpServletResponse response, Object object) {
		return renderString(response, JsonMapper.toJsonString(object));
	}
	
	public UserEntity getWebSysUserAttribute(String name) {
		UserEntity tuser = null;
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		if (ra != null) {
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			if (!name.trim().equals("")) {
				tuser = (UserEntity) request.getSession().getAttribute(name);
			}
		}
		return tuser;
	}
	
	public Long GetLoginUserId(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			return entity.getUserid();
		}
		catch(Exception ex){
			return -1L;
		}
	}
	
	public UserEntity GetLoginUser(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			return entity;
		}
		catch(Exception ex){
			return null;
		}
	}

	public UserEntity GetUserById(Long userid){
		try {
		 return iUserService.GetUserById(userid);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String GetLoginUserOrgids(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getMaxroletype()>0){
				return iAccountService.GetOrgidsByRoleId(entity.getUserid(),entity.getSzdw());
			}
			else{
				return "-1";
			}
		}
		catch(Exception ex){
			return null;
		}
	}
	
	public String GetLoginUserOrgidsForOrg(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getMaxroletype()>0){
				return iAccountService.GetOrgidsByRoleId(entity.getUserid(),entity.getSzdw());
			}
			else{
				return entity.getSzdw().toString();
			}
		}
		catch(Exception ex){
			return null;
		}
	}

	public List<OrgEntity> GetOrgListByOrgid(Long orgid) {
		List<OrgEntity> lst=new ArrayList<>();
		try
		{
			String where="";
			if(orgid != 19) {
				where = " AND orgparentid=" + orgid + " OR orgid=" + orgid;
				lst = iOrgService.GetOrgListByWhere(where);
			}
			return  lst;
		}
		catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}

	public List<OrgEntity> getOrgEntities() throws Exception {
		String where=" AND orgid IN ("+this.GetOrgListByRole()+")";
		List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
		for (int i = 0; i < orglst.size(); i++) {
			String html="";
			for(int j=0;j<orglst.get(i).getLevel();j++){
				html+="&#12288;";
			}
			orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
		}
		return orglst;
	}

	public List<OrgEntity> getOrgEntitiesAll() throws Exception {
		String where="AND orgtype = 0";
		List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
		for (int i = 0; i < orglst.size(); i++) {
			String html="";
			for(int j=0;j<orglst.get(i).getLevel();j++){
				html+="&#12288;";
			}
			orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
		}
		return orglst;
	}
	
	public String GetLoginUserOrgidWhereForOrg(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			String orgids=iAccountService.GetOrgidsByRoleId(entity.getUserid(),entity.getSzdw());
			return " AND orgid IN ("+orgids+")";
		}
		catch(Exception ex){
			return null;
		}
	}
	
	public String GetLoginUserForUserListWhere(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getMaxroletype()>0){
				String strorgids=iAccountService.GetOrgidsByRoleId(entity.getUserid(),entity.getSzdw());
				
				return " AND SZDW IN ("+strorgids+")";
			}
			else{
				return " AND userid="+entity.getUserid();
			}
		}
		catch(Exception ex){
			return null;
		}
	}
	
	public String GetLoginUserForOtherListWhereByUserId(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getMaxroletype()>0){
				String strorgids=iAccountService.GetOrgidsByRoleId(entity.getUserid(),entity.getSzdw());
				
				return " AND userid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+strorgids+"))";
			}
			else{
				return " AND userid="+entity.getUserid();
			}
		}
		catch(Exception ex){
			return null;
		}
	}
	
	public String GetLoginUserForOtherListWhereByCreateUserId(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getMaxroletype()>0){
				String strorgids=iAccountService.GetOrgidsByRoleId(entity.getUserid(),entity.getSzdw());
				
				return " AND byuserid IN (SELECT userid FROM t_sys_user WHERE SZDW IN ("+strorgids+"))";
			}
			else{
				return " AND byuserid="+entity.getUserid();
			}
		}
		catch(Exception ex){
			return null;
		}
	}
	
	public String GetOrgListByRole(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getUserid()>0){
                String strorgids=iAccountService.GetOrgidsByUserRoleId(entity.getRoleid());
				return strorgids;
			}
			else{
				return "";
			}
		}
		catch(Exception ex){
			return null;
		}
	}
	
	public String GetUserListByRole(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getUserid()>0){
                String strorgids=iAccountService.GetOrgidsByUserRoleId(entity.getRoleid());
				if(strorgids!=null&&strorgids.length()>0){
					return " AND szdw IN ("+strorgids+") ";
				}
				else{
					return " AND userid="+entity.getUserid();
				}
               
			}
			else{
				return "";
			}
		}
		catch(Exception ex){
			return null;
		}
	}
	
	public String GetUserListByRoleForNotUser(){
		try{
			UserEntity entity=getWebSysUserAttribute("UserEntity");
			if(entity.getUserid()>0){
                String strorgids=iAccountService.GetOrgidsByUserRoleId(entity.getRoleid());
				if(strorgids!=null&&strorgids.length()>0){
					return "  AND userid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+strorgids+")) ";
				}
				else{
					return " AND userid="+entity.getUserid();
				}
               
			}
			else{
				return "";
			}
			
			
		}
		catch(Exception ex){
			return null;
		}
	}
	


	

	protected String renderString(HttpServletResponse response, String string) {
		try {
			response.reset();
	        response.setContentType("application/json");
	        response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			response.getWriter().flush();
			response.getWriter().close();
			return null;
		} catch (IOException e) {
			return null;
		}
	}
	
	protected String renderStringScript(HttpServletResponse response, String string) {
		try {
			response.reset();
	        response.setContentType("text/html");
	        response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			response.getWriter().flush();
			response.getWriter().close();
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	@ExceptionHandler({BindException.class, ConstraintViolationException.class, ValidationException.class})
    public String bindException() {  
        return "error/400";
    }
	

	@ExceptionHandler({AuthenticationException.class})
    public String authenticationException() {  
        return "error/403";
    }
	

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}
		});
	}
}
